var userId, userName;

var viewModel = new function () {
    this.ShowNoResult = ko.observable(false);
    this.ShowResultSearch = ko.observable();
    this.SearchKeyWord = ko.observable("");

    this.dataUserList = ko.observableArray(data.UserList);
    this.dataAssign = ko.observableArray(data.ListUserAssign);
    this.totalUsers = ko.observable(data.NumberOfUsers);

    this.NumberOfLicenses = ko.observable(data.NumberOfLicenses);
    this.NumberOfUsers = ko.observable(data.NumberOfUsers);
    this.ColName = ko.observable("Name");
    this.SortOrder = ko.observable("desc");

    this.PageSize = ko.observable(data.RecordPerPage);
    this.MaxPageIndex = ko.computed(function () {
        return Math.ceil(ko.utils.unwrapObservable(this.dataUserList().length / this.PageSize()));
    }, this);
    this.CurrentPageIndex = ko.observable(1);

    this.itemsOnCurrentPage = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, ''),
			pagesize = parseInt(pagevalue, 10);

        if (isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
            return "";
        }
        else {
            var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1),
				endIndex = parseInt(startIndex) + parseInt(this.PageSize());

            return this.dataUserList.slice(startIndex, endIndex);
        }

    }, this);

    this.ShowResultSearch = ko.computed(function () {
        return !this.ShowNoResult();
    }, this);

    this.DialIq = ko.observable(data.DialIq);
    this.DialIqNote = ko.observable(data.DialIq == null || data.DialIq.toString().toLowerCase() == "false");
    this.UserOption = ko.observable();
    this.UserSelected = ko.observable('');
    this.UserOptions = ko.observableArray([]);

    this.UserAssign = ko.computed(function () {
        var strUserId = this.UserSelected();

        //alert(this.dataAssign().length);
        var _ListUserAssign = ko.utils.arrayFilter(this.dataAssign(), function (option) {
            return option.UserId != strUserId;
        });

        this.UserOptions(_ListUserAssign);

        // Refresh JCF dropdown box
        var tempEl = document.getElementById("userOptionSelect");
        if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
        jcf.customForms.replaceElement("userOptionSelect");
        // Must be executed after knockout rendering
        setTimeout("jcf.customForms.replaceElement('userOptionSelect')", 0);

    }, this);


    function SetResultString(strResult) {
        //viewModel.SearchKeyWord('No results were found for \u201C' + strResult + '\u201D.');
        viewModel.SearchKeyWord("No results were found.");
    };

    //////////////////////////////////////////// EVENT ////////////////////////////////////////
    this.AssignDeleteUser = function () {

        if (viewModel.ValidateOptionUser()) {
            var userId = $('#reassignUserId').val(),
				userIdAssign = $("#userOptionSelect").val(),
				dataPost = { "userid": userId, "userIdAssign": userIdAssign };

            closeReassignLead();

            // Json Get function to retrive data from server
            openProcessBar();

            $.ajax({
                type: "POST",
                url: "/User/RemoveUserHaveLead",
                data: dataPost,
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    if (data && (typeof data.Error == "undefined" || !data.Error)) {
                        viewModel.dataUserList(data.UserList);

                        var list = viewModel.dataAssign();
                        viewModel.dataAssign([]);

                        for (var i = 0; i < list.length; i++) {
                            if (list[i].UserId == userId) {
                                list.splice(i, 1);
                            }
                        }
                        viewModel.dataAssign(list);

                        viewModel.totalUsers(data.NumberOfUsers);
                        viewModel.NumberOfLicenses(data.NumberOfLicenses);
                        viewModel.NumberOfUsers(data.NumberOfUsers);

                        hideProcessBar();
                        closeReassignLead();
                    }
                    else {
                        hideProcessBar();
                        showPopupError();
                    }
                },
                error: function (xhr, status, error) {
                    hideProcessBar();
                    showPopupError();
                }
            }); // End ajax post
        }
    };

    this.CheckBuyLicense = function () {
        closeNewUserAlert();

        // Json Get function to retrive data from server
        openProcessBar();

        $.ajax({
            type: "POST",
            url: "/User/BuyLicense",
            data: {},
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data && (typeof data.Error == "undefined" || !data.Error)) {
                    if (data) {
                        var url = "/User/Create";
                        window.redirect = url;
                        document.location = url;
                    }

                    hideProcessBar();
                }
                else {
                    hideProcessBar();
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {
                hideProcessBar();
                showPopupError();
            }
        }); // End ajax post
    };

    this.ValidateOptionUser = function () {
        var validationResult = true;
        if (viewModel.UserOption() == "0") {
            $("#ErrorUserMessage").show();
            $('#ErrorUserMessage').text("Please select an user");
            validationResult = false;
        }

        return validationResult;
    };

    this.DeletePermanent = function () {
        var userId = $('#permanentUserId').val(),
			dataPost = { "userid": userId };

        closePermanentPopup();

        // Json Get function to retrive data from server
        openProcessBar();

        $.ajax({
            type: "POST",
            url: "/User/RemoveUserNoLead",
            data: dataPost,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data && (typeof data.Error == "undefined" || !data.Error)) {
                    viewModel.dataUserList(data.UserList);

                    var list = viewModel.dataAssign();
                    viewModel.dataAssign([]);

                    for (var i = 0; i < list.length; i++) {
                        if (list[i].UserId == userId) {
                            list.splice(i, 1);
                        }
                    }
                    viewModel.dataAssign(list);

                    viewModel.totalUsers(data.NumberOfUsers);
                    viewModel.NumberOfLicenses(data.NumberOfLicenses);
                    viewModel.NumberOfUsers(data.NumberOfUsers);

                    hideProcessBar();
                    closePermanentPopup();
                }
                else {
                    hideProcessBar();
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {

                hideProcessBar();
                showPopupError();
            }
        }); // End ajax post
        return false;
    };

    $('#searchKeyword').keyup(function (e) {
        if (e.keyCode == 13) { //Enter key
            SearchData();
        }
    });

    // Handler click Search button
    this.SearchButton = function () {
        SearchData();
    };

    function SearchData() {
        // Get search keyword and trim form inputbox
        var searchOrg = $.trim($('#searchKeyword').val()),
			searchKey = searchOrg.toLowerCase();

        if (searchKey != "") {
            // Json Get function to retrive data from server
            openProcessBar();

            $.ajax({
                type: "POST",
                url: "/User/GetAllData",
                data: {},
                dataType: "json",
                success: function (returnData, textStatus, jqXHR) {
                    if (returnData && (typeof returnData.Error == "undefined" || !returnData.Error)) {
                        if (returnData.length > 0) {
                            if (searchKey != "search users") {
                                var filteredData = jQuery.grep(returnData, function (element, index) {
                                    // Get all objects name match with searchKeyword
                                    return element.Name.toLowerCase().match(searchKey);
                                });
                                viewModel.dataUserList(filteredData);

                                if ((filteredData != null) && (filteredData.length > 0)) {
                                    viewModel.CurrentPageIndex(1);
                                    viewModel.ShowNoResult(false);
                                }
                                else {
                                    viewModel.CurrentPageIndex(0);
                                    viewModel.ShowNoResult(true);
                                    SetResultString(searchOrg);
                                }
                            }
                            else {
                                viewModel.dataUserList(returnData);
                                viewModel.CurrentPageIndex(1);
                                viewModel.ShowNoResult(false);
                            }
                            ClearSortImage();
                        }
                        else {
                            viewModel.dataUserList([]);
                            viewModel.CurrentPageIndex(0);
                            viewModel.ShowNoResult(true);
                            SetResultString(searchOrg);
                            ClearSortImage();
                        }

                        hideProcessBar();
                    }
                    else {
                        hideProcessBar();
                        showPopupError();
                    }
                },
                error: function (xhr, status, error) {
                    hideProcessBar();
                    showPopupError();
                }
            }); // End ajax post
        }
        else {  // Get all data
            // Json Get function to retrive data from server
            openProcessBar();

            $.ajax({
                type: "POST",
                url: "/User/GetAllData",
                data: {},
                dataType: "json",
                success: function (returnData, textStatus, jqXHR) {
                    if (returnData && (typeof returnData.Error == "undefined" || !returnData.Error)) {

                        if (returnData.length > 0) {
                            viewModel.dataUserList(returnData);
                            viewModel.CurrentPageIndex(1);
                            viewModel.ShowNoResult(false);
                            ClearSortImage();
                        }

                        hideProcessBar();
                    }
                    else {
                        hideProcessBar();
                        showPopupError();
                    }
                },
                error: function (xhr, status, error) {

                    hideProcessBar();
                    showPopupError();
                }
            }); // End ajax post
        }
    }
    var _numberOfLicenses = this.NumberOfLicenses();
    //var _numberOfLicenses = 30;
    this.AddNewBtnClick = function () {
        var maxUserInExpress = data.MaxUserInExpress;
        var totalUsers = this.totalUsers();
        if (totalUsers < _numberOfLicenses) {
            var url = "/User/Create";
            window.redirect = url;
            document.location = url;
        }
        else {
            if (totalUsers >= maxUserInExpress) {
                $('#alertTooManyUsers').showPopup({
                    width: 550
                });
                $('#fancybox-overlay').show();
            }
            else {
                $('#newUserAlert').showPopup({
                    width: 470
                });
                $('#fancybox-overlay').show();
            }
        }

    }

    ////////////////////////////// PAGING /////////////////////////////////////
    this.PageSizeText = ko.computed(function () {
        if (this.dataUserList().length > 0) {
            var pagevalue = this.PageSize().toString().replace(/\s/g, ''),
				pagesize = parseInt(pagevalue, 10);
            //alert(pagesize);
            this.CurrentPageIndex(1);
            if (!IsNumeric(pagevalue)) {
                return "* Please enter a number between 1 - 100";
            }
            else if (isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
                return "* Please enter a number between 1 - 100";
            }
            else {
                return "";
            }
        }

    }, this);
    this.PageCurrentText = ko.computed(function () {
        if (this.dataUserList().length > 0) {
            var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, ''),
				pageindex = parseInt(pagevalue, 10),
				pagesize = parseInt(this.PageSize().toString().replace(/\s/g, ''), 10);

            if (isNaN(pagesize) || pagesize == 0) {
                return "";
            }
            else if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "") {
                return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
            }
            else if (isNaN(pagevalue) || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
                return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
            }
            else {
                return "";
            }
        }
        else {
            return "";
        }

    }, this);

    // Paginate
    this.PreviousPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
        }
    }
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            return "btn btn-prev-arrow prev-active";
        }
        else {
            return "btn btn-prev-arrow";
        }
    }, this);

    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
        }
    }
    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
            return "btn btn-next-arrow next-disabled";
        else
            return "btn btn-next-arrow";
    }, this);


    // PageSize/ PageCurrent keypress enter
    this.RunSomethingKey = function (viewModel, event) {
        if (event.keyCode == 13) {
            this.RunSomething(viewModel, event);
        }
        return true;
    }
    this.RunSomething = function (viewModel, event) {
        LoadDataKeyPresss();
    }

    function LoadDataKeyPresss() {
        // Page Size
        var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, ''),
			pagesize = parseInt(pageSizeValue, 10);
        if (!IsNumeric(pageSizeValue) || isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
            return false;
        }

        // Page Index
        var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, ''),
			pageindex = parseInt(pageIndexValue, 10);
        if (!IsNumeric(pageIndexValue) || isNaN(pageindex) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            return false;
        }
    }

    ///////////////////////////////////// SORTING //////////////////////////////////////////
    function SetTHClass(event, colName) {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc desc");

        var sortOrder = viewModel.SortOrder();
        if (!sortOrder || $.trim(sortOrder).toLowerCase() === "asc") {
            $("#" + colName).children("span").addClass("asc");
        }
        else {
            $("#" + colName).children("span").addClass("desc");
        }
    }

    function SwitchSortOrder() {
        var sortOrder = this.SortOrder();
        if (!sortOrder || $.trim(sortOrder).toLowerCase() === "asc") {
            this.SortOrder("desc");
        } else {
            this.SortOrder("asc");
        }
    }
    this.SwitchSortOrder = SwitchSortOrder;
    // Sort by Colum/Order
    function SetOrder(event, ColName) {

        if (this.ColName() === ColName) {
            this.SwitchSortOrder();
        } else {
            this.ColName(ColName);
            this.SortOrder("asc");
        }
        SetTHClass(event, ColName);
        if (ColName != "") {
            this.dataUserList(SortByPropertyName(ko.utils.unwrapObservable(this.dataUserList()), ColName, this.SortOrder()));
        }
    }
    this.SetOrder = SetOrder; // Set to an knockout object

    // sort all items
    function SortByPropertyName(items, propertyName, sortOrder) {
        return items.sort(sortProperty(propertyName, sortOrder));
    }

    function sortProperty(property, sortOrder) {
        if (!sortOrder || $.trim(sortOrder).toLowerCase() == "asc") {
            return function (a, b) {
                var number = parseFloat($.trim(a[property])),
					numberb = parseFloat($.trim(b[property]));

                if (!isNaN(number) && number > 0 && number.toString().length == a[property].toString().length) {
                    return (number < numberb) ? -1 : ((number > numberb) ? 1 : 0);
                }
                else {
                    return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1
						: ((a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0);
                }
            }
        }
        else {
            return function (a, b) {
                var number = parseFloat($.trim(a[property])),
					numberb = parseFloat($.trim(b[property]));

                if (!isNaN(number) && number > 0 && number.toString().length == a[property].toString().length) {
                    return (number > numberb) ? -1 : ((number < numberb) ? 1 : 0);
                }
                else {
                    return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1
						: ((a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0);
                }
            }
        }
    }

};

ko.applyBindings(viewModel, document.getElementById('viewUsers'));


function doEditLinks() {
	var jObj = $(this);

	userId = jObj.attr("href").replace(/^.+?(\d+)$/, "$1");
	userName = jObj.attr("value").replace(/^#+/, "");

	return true;
}

function doEnableLinks() {
	var jObj = $(this);

	var receivingId = jObj.attr("id"),
		userId = jObj.attr("href").replace(/^#+/, ""),
		enable = jObj.attr("rel");

	// Update status
	UpdateReceivingStatus(receivingId, userId, enable);

	return false;
}

// Combine 2 functions doEditLinks() and doEnableLinks() into this one
function refreshRowLinks(els) {
	if (els && els.length) {

		for (var i = 0; i < els.length; i++) {
			// Re-bind on-click event for each edit-links
			$("a.email_link", els[i]).unbind("click", doEditLinks).bind("click", doEditLinks);

			// Re-bind on-click event for each receiving-links
			$("a.receiving", els[i]).unbind("click", doEnableLinks).bind("click", doEnableLinks);
		}
	}
}

// Update receiving status.
function UpdateReceivingStatus(receivingId, _userId, enable) {
	enable = ($.trim(enable).toLowerCase() == "true") ? "false" : "true";

	// Check exist leads
	var dataPost = { "agentId": _userId, "status": enable };
	if (/toggle\-lead/i.test(receivingId)) {

	    $.ajax({
	        type: "POST",
	        url: "/User/UpdateReceivingLead",
	        data: dataPost,
	        dataType: "json",
	        success: function (returnData, textStatus, jqXHR) {
	            if (!returnData) {
	                UpdateClass(receivingId, enable);
	                UpdateStatus(receivingId, _userId, enable);
	            }
	        },
	        error: function (xhr, status, error) {
	            showPopupError();
	        }
	    });
	}
	else if (/toggle\-call/i.test(receivingId)) {

	$.ajax({
	    type: "POST",
	    url: "/User/UpdateReceivingCall",
	    data: dataPost,
	    dataType: "json",
	    success: function (returnData, textStatus, jqXHR) {
	        if (!returnData) {
	            UpdateClass(receivingId, enable);
	            UpdateStatus(receivingId, _userId, enable);
	        }
	    },
	    error: function (xhr, status, error) {
	        showPopupError();
	    }
	});
	}
}

function UpdateClass(receivingId, enable) {
	if ($.trim(enable).toLowerCase() == "true") {
		$("#" + receivingId).removeClass("toggle-off").addClass("toggle-on").attr("rel", "true");
	}
	else {
		$("#" + receivingId).removeClass("toggle-on").addClass("toggle-off").attr("rel", "false");
	}
}

function UpdateStatus(receivingId, _userId, enable) {
	try {
		enable = ($.trim(enable).toLowerCase() == "true") ? true : false;

		if (viewModel.dataUserList().length > 0) {
			var list = viewModel.dataUserList();
			viewModel.dataUserList([]);

			for (var i = 0; i < list.length; i++) {
				if (list[i].UserId == _userId) {
					if (/toggle\-lead/i.test(receivingId))
						list[i].ReceivingLead = enable;
					else if (/toggle\-call/i.test(receivingId))
						list[i].ReceivingCall = enable;

					break;
				}
			}

            viewModel.dataUserList(list);
		}
	}
	catch (e) {
		// DEBUG
		if (typeof console != "undefined") console.log(e);
	}
}

function ClearSortImage() {
	$("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc desc");
}

function OpenReassignLead(userId) {
	// Check exist leads
	var dataPost = { "userid": userId };

	$.ajax({
		type: "POST",
		url: "/User/CheckLeadOfUser",
		data: dataPost,
		dataType: "json",
		success: function (returnData, textStatus, jqXHR) {
			if (returnData == true) { // Have assigned
				// Set default for dropdownlist
				viewModel.UserOption(data.ListUserAssign[0].UserId);
				//$('#ddlUserList').find("span.jcf-unselectable").text("Select User");
				$('#ErrorUserMessage').hide();

				$('#reassignUserId').val(userId);
				userName = $('#user_' + userId).attr("rel");
				$('#userName').text(userName);

				viewModel.UserSelected(userId);

				// Show popup
				$('#confirmDeleteUser').showPopup({
					width: 500
				});
				$('#fancybox-overlay').show();
			}
			else { // Delete permanent
				$('#permanentUserId').val(userId);

				$('#deletePermanent').showPopup({
					width: 400
				});
				$('#fancybox-overlay').show();
			}
		},
		error: function (xhr, status, error) {
			showPopupError();
		}
	});
}


function closeReassignLead() {
	//$('#ErrorUserMessage').hide();
	$('#confirmDeleteUser').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}
function closePermanentPopup() {
	$('#deletePermanent').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}
function closeAlertTooManyUsers() {
	$('#alertTooManyUsers').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}
function closeNewUserAlert() {
	$('#newUserAlert').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}

function userKeyUp(evt) {
	if ($("#ddlUserList").find('.center').text() != "Select Company")
		$("#ErrorUserMessage").hide();
}


$(document).ready(function () {
	var textDefault = "Search Users";
	$("#searchKeyword").focus(function() {
		var el = $(this);
		if (el.val() != null && $.trim(el.val()).toLowerCase() == textDefault.toLowerCase()) {
			el.val("");
		}
	}).blur(function() {
		var el = $(this);
		if (el.val() == null || $.trim(el.val()) == "") {
			el.val(textDefault);
		}
	});
});

// Progress Bar
function openProcessBar() {
    $.fancybox($('#popup-process'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.6,
                css: {
                    'background-color': '#11619D'
                }
            }
        },
        beforeClose: function () {
            return false;
        }
    });
    $('.fancybox-skin').show();
    $('#fancybox-overlay').show();
}
function hideProcessBar() {
    $('#popup-process').hide();
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
}